﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Reflection;
using System.ServiceModel;
using System.ServiceModel.Description;
using System.ServiceModel.Channels;
using System.IO;
using System.Data;
using System.Data.SqlClient;
using System.Security.Cryptography;
using System.Xml;
using DaInterFace;
using DaInterFace.PDA;

namespace DaFunction.PDA
{
    [ServiceContract()]
    public interface IPDAApi
    {
        [OperationContract]
        LoginResult Login(LoginParameters p);

        [OperationContract]
        void Logout(PDAClient clinet);

        [OperationContract]
        String Code(String parameter);
    }

    [ServiceBehavior(InstanceContextMode = InstanceContextMode.PerSession)]
    public class PDAApi : IPDAApi
    {
        private const String PublicKey = "V63JxeExiKi0ZziL";

        public static IPDA DaPDA;

        private static Dictionary<string, PDAUser> UserDictionary = new Dictionary<string, PDAUser>();

        public LoginResult Login(LoginParameters p)
        {
            LoginResult cr = new LoginResult();
            PDAUser mu = new PDAUser();

            try
            {
                SqlParameter[] sps = new SqlParameter[1];
                sps[0] = new SqlParameter("@Number", SqlDbType.NVarChar, 50);
                sps[0].Value = p.UserNumber;

                String sql = "SELECT FName,FNumber,FText Pswd,FComboBox UserType FROM KEW_DeviceUserEntry WHERE FNumber=@Number";
                Recordset rs = DaPDA.Data.ExeBase(sql, sps);

                if (rs.Enable)
                {
                    if (rs.Data.Tables[0].Rows.Count != 1)
                    {
                        cr.Enable = false;
                        cr.Message = "用户名错误";
                    }
                    else if (rs.Data.Tables[0].Rows[0]["Pswd"].ToString() != p.PassWord)
                    {
                        cr.Enable = false;
                        cr.Message = "密码错误";
                    }
                    else
                    {
                        UserDictionary.Remove(p.UserNumber);

                        mu.Key = Guid.NewGuid().ToString();
                        mu.IMEI = p.IMEI;
                        mu.UserName = rs.Data.Tables[0].Rows[0]["FName"].ToString();
                        mu.UserNumber = rs.Data.Tables[0].Rows[0]["FNumber"].ToString();
                        mu.LoginTime = DateTime.Now;
                        mu.VisitTime = DateTime.Now;
                        mu.UserType = rs.Data.Tables[0].Rows[0]["UserType"].ToString();
                        UserDictionary.Add(mu.UserNumber, mu);

                        cr.Enable = true;
                        cr.Key = mu.Key;
                        cr.UserNumber = mu.UserNumber;
                        cr.UserName = mu.UserName;
                        cr.UserType = mu.UserType;
                        cr.VistSpan = Common.CInt(DaPDA.Config.Get("Vist"));
                        //DaMobile.Message(MessageType.Note, String.Format("用户[{0}]登录成功，IMEI：{1},IP:{2}", p.UserName, p.IMEI, endpoint.Address));
                        DaPDA.Message(MessageType.Note, String.Format("用户{0}[{1}]登录成功，IMEI：{2}", mu.UserNumber, mu.UserName, mu.IMEI));
                    }

                }
                else
                {
                    cr.Enable = false;
                    cr.Message = rs.Message;
                }


            }
            catch (Exception ex)
            {
                cr.Enable = false;
                cr.Message = ex.Message;
            }

            return cr;
        }

        public void Logout(PDAClient clinet)
        {
            if (CheckUser(clinet) == 0)
            {
                UserDictionary.Remove(clinet.UserNumber);
                DaPDA.Message(MessageType.Note, String.Format("用户{0}注销下线了。", clinet.UserNumber));
            }
        }

        private int CheckUser(PDAClient pc)
        {
            if (UserDictionary.ContainsKey(pc.UserNumber))
            {
                if (UserDictionary[pc.UserNumber].IMEI == pc.IMEI && UserDictionary[pc.UserNumber].Key == pc.Key)
                {
                    UserDictionary[pc.UserNumber].VisitTime = DateTime.Now;
                    return 0;
                }
                else
                {
                    return 1;
                }
            }
            else
            {
                return 2;
            }
        }

        private PDACodeUser ConvertUserClass(PDAUser mu)
        {
            PDACodeUser cu = new PDACodeUser();
            cu.UserName = mu.UserName;
            cu.UserNumber = mu.UserNumber;
            cu.LoginTime = mu.LoginTime;
            cu.VisitTime = mu.VisitTime;

            return cu;
        }

        public String Code(String parameters)
        {
            CodeResult result = new CodeResult();
            try
            {
                DateTime curtime = DateTime.Now;
                PDAParameter mp = (PDAParameter)DaPDA.XML.Deserialize(typeof(PDAParameter), parameters);
                String[] splitCode = mp.CodeName.Split('.');

                if (splitCode.Length != 2)
                {
                    result.Result = EnumResult.Error;
                    result.Message = "错误的功能代码！";

                    return DaPDA.XML.Serializer(typeof(CodeResult), result);
                }

                String file = splitCode[0];
                String code = splitCode[1];

                int crst = CheckUser(mp.Client);

                switch (crst)
                {
                    case 0:
                        try
                        {
                            PDAUser serveruser = UserDictionary[mp.Client.UserNumber];
                            PDACodeUser user = ConvertUserClass(serveruser);
                            Assembly ass = Assembly.Load(file);  //加载dll文件
                            Type tp = ass.GetType(file + "." + code);  //获取类名，必须 命名空间+类名
                            IPDAChild temp = (IPDAChild)Activator.CreateInstance(tp);  //建立实例
                            temp.Code(DaPDA, result, user, mp.Parameters);
                            DaPDA.Message(MessageType.Note, mp.CodeName + ":" + result.Message, (DateTime.Now - curtime).TotalMilliseconds);
                        }
                        catch (Exception ex)
                        {
                            result.Result = EnumResult.Error;
                            result.Message = "Code代码错误，请联系管理人员：" + mp.CodeName + ex.Message;
                            DaPDA.Message(MessageType.Error, mp.CodeName + ":" + ex.Message, (DateTime.Now - curtime).TotalMilliseconds);
                        }
                        break;
                    case 1:
                        result.Result = EnumResult.ReLoad;
                        result.Message = "无效的登录信息，请重新登录。";
                        break;
                    case 2:
                        result.Result = EnumResult.ReLoad;
                        result.Message = "请先登录。";
                        break;
                }
            }
            catch (Exception ex)
            {
                result.Result = EnumResult.Error;
                result.Message = ex.Message;
            }

            return DaPDA.XML.Serializer(typeof(CodeResult), result);
        }
    }
}
